package com.itheima.aop;
import java.time.LocalDateTime;
import java.util.Arrays;

import com.itheima.Utils.ThreadLocalUtils;
import com.itheima.mapper.LogInfoMapper;
import com.itheima.pojo.LogInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 *  AOP记录运行日志
 * @author GY
 * @version V1.0
 * @date 2025-01-19 10:48
 */
@Slf4j
@Component
@Aspect
@RequiredArgsConstructor
public class LogAspect {
    private final LogInfoMapper logInfoMapper;

    @Pointcut("execution(* com.itheima.controller.*.*(..))")
    public void pc(){}

    @Around("@annotation(com.itheima.annotation.LogAnno)")
    public Object logMethod(ProceedingJoinPoint pjp) throws Throwable {
        long begin = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        LogInfo logInfo = new LogInfo();
        logInfo.setOperateName(ThreadLocalUtils.get());
        logInfo.setOperateTime(LocalDateTime.now());
        logInfo.setClassName(pjp.getTarget().getClass().getName());
        logInfo.setMethodName(pjp.getSignature().getName());
        Object[] args = pjp.getArgs();
        if (ObjectUtils.isEmpty(args)){
            args=new Object[]{""};
        }
        logInfo.setParams(Arrays.asList(args).toString());
        if (ObjectUtils.isEmpty(result)){
            result="";
        }
        logInfo.setReturnValue(result.toString() );
        logInfo.setRuntimeValue((int) (end-begin));

        logInfoMapper.insertLogInfo(logInfo);
        return result;

    }

}
